package com.nus.servlets;

import com.nus.beans.Project;
import com.nus.beans.User;
import com.nus.database.UserDBManager;
import com.nus.database.UserInfoDBManager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/21/12
 * Time: 12:02 AM
 * To change this template use File | Settings | File Templates.
 */
public class ViewInfoServlet extends AbstractServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doGet(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        Connection connection = getUserDatabaseConnection(request);
        UserInfoDBManager infoManager = new UserInfoDBManager(connection);
        int userId;
        User user = null;
        String userIdParam = request.getParameter("users");
        Integer targetUserID;
        targetUserID = (Integer) request.getAttribute("targetUserId");

        UserDBManager userDBManager = new UserDBManager(connection);
        if (targetUserID != null) {
            userId = targetUserID;
            user = userDBManager.getUser(targetUserID);
        } else if (userIdParam == null) {
            user = (User) request.getSession().getAttribute("user");
            userId = user.getUserId();
            user = userDBManager.getUser(userId);
        } else {
            userId = Integer.parseInt(userIdParam);
            user = userDBManager.getUser(userId);

        }

        request.setAttribute("targetUser", user);

        List<Project> projects = infoManager.getUserProjects(userId);
        request.setAttribute("projects", projects);

        String targetPage = (String) request.getAttribute("targetPage");
        if (targetPage == null) {
            targetPage = "/WEB-INF/developer_info.jsp";
        }

        infoManager.close();

        RequestDispatcher dispatcher = request.getRequestDispatcher(targetPage);
        dispatcher.forward(request, response);
    }
}
